package com.hdu.clj.fitness

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.text.isDigitsOnly
import kotlinx.android.synthetic.main.activity_reg.*
import java.io.*

class RegActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_reg)
        ActivityCollector.addActivity(this)

        if (agreeReg.isChecked){
            reg.isEnabled = true
            reg.isClickable = true
            reg.setBackgroundColor(Color.parseColor("#3BFFC022"))
        }
        else{
            reg.isEnabled = false
            reg.isClickable = false
            reg.setBackgroundColor(Color.parseColor("#CECFD8"))
        }
        agreeReg.setOnClickListener {
            if (agreeReg.isChecked){
                reg.isEnabled = true
                reg.isClickable = true
                reg.setBackgroundColor(Color.parseColor("#3BFFC022"))
            }
            else{
                reg.isEnabled = false
                reg.isClickable = false
                reg.setBackgroundColor(Color.parseColor("#CECFD8"))
            }
        }

        val userName = nameMakeLog.text
        val userPass = passMakeLog.text
        val userRePass = rePassLog.text
        val userAcc = accMakeLog.text
        var ver = 1
        reg.setOnClickListener {
            val dbHelper = userDatabase(this,"Users.db",1)
            val db = dbHelper.writableDatabase
            if (userName.isNotEmpty()&&userPass.isNotEmpty()&&userRePass.isNotEmpty()&&userAcc.isNotEmpty()){
                if (!withSimbol(userAcc.toString())){
                    if (userPass.toString().equals(userRePass.toString())) {
                        val sname = db.rawQuery("select * from Users where acc = ?", arrayOf(userAcc.toString()))
                        if (sname.moveToFirst()){
                            Toast.makeText(this, "账号已存在!", Toast.LENGTH_SHORT).show()
                        }
                        else{
                            val values = ContentValues().apply {
                                put("acc", userAcc.toString())
                                put("pass", userPass.toString())
                                put("dayNum",1000)
                                put("totalNum",10000)
                                put("total",0)
                                put("cardNum",0)
                                put("curTotal",0)
                                put("name",userName.toString())
                            }
                            db.insert("Users", null, values)
                            if (load("ver").isNotEmpty()){
                                ver = load("ver").toInt()
                            }

                            Toast.makeText(this, "注册成功!", Toast.LENGTH_SHORT).show()
                            val dbDayNum = DayNumDatabase(this,"Fit.db",ver,"abc"+userAcc.toString())
                            dbDayNum.writableDatabase
                            save(ver+1,"ver")
                            Log.d("curdata","reg $userAcc ver $ver")
                            Log.d("curdata","tab $userAcc ver $ver")
                        }
                        sname.close()
                    }
                    else{
                        Toast.makeText(this,"两次输入的密码不一致",Toast.LENGTH_SHORT).show()
                    }
                }
                else{
                    Toast.makeText(this, "账号不能包含特殊字符！", Toast.LENGTH_SHORT).show()
                }
            }
            else {
                Toast.makeText(this, "请输入完整的内容！", Toast.LENGTH_SHORT).show()
            }
        }
        regText.setOnClickListener {
            val intent = Intent(this,ShowRegTextActivity::class.java)
            startActivity(intent)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }
    private fun save(inputText: Int,data:String) {
        try {
            val output = openFileOutput(data, Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                it.write(inputText.toString())
            }
        }catch (e: IOException){
            e.printStackTrace()
        }
    }

    private fun load(data:String): String {
        val content = StringBuilder()

        try {
            val input = openFileInput(data)
            //val reader = BufferedReader(InputStreamReader(input))
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        }catch (e: IOException){
            e.printStackTrace()
        }
        return content.toString()
    }

    private fun withSimbol(str:String):Boolean{
        val len = str.length
        for (i in 0 until len){
            if (!(str[i]>='0'&&str[i]<='9')&&!(str[i]>='a'&&str[i]<='z')&&!(str[i]>='A'&&str[i]<='Z')){
                return true
            }
        }
        return false
    }
}
